/*
 * @lc app=leetcode.cn id=437 lang=javascript
 *
 * [437] 路径总和 III
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number}
 */
var pathSum = function (root, targetSum) {
  let count = 0;
  let help = function (node, arr) {
    let value = node.val;
    if(value===targetSum)count++
    node.values = arr.map((item) => {
      let temp = item + value;
      if(temp===targetSum)count++
      return temp
    }).concat(value);
  };
  let dfs = function (node, arr) {
    if (!node) return;
    help(node,arr)
    dfs(node.left,node.values)
    dfs(node.right,node.values)
  };
  dfs(root,[]);
  return count;//动态规划
};
// @lc code=end

var pathSum = function (root, targetSum) {
  let count = 0;
  let help = function (node, target) {
    if (!node) return;
    if (target - node.val == 0) {
      count++;
    }
    help(node.left, target - node.val);
    help(node.right, target - node.val);
  };
  let dfs = function (root) {
    if (!root) return;
    help(root, targetSum);
    dfs(root.left);
    dfs(root.right);
  };
  dfs(root);
  return count;
}; //BF解法
